const Service = require('egg').Service

class TreeService extends Service {
  async getColumn() {
    const { ctx, app } = this
    const res = await ctx.find('CourseColumn', {
      include: {
        model: app.model.CourseCategory,
        attributes: ['id', 'channelId', 'categoryId', 'categoryName']
      }
    }, 'findAll')
    const columnRes = []
    res.forEach(item => {
      const index = columnRes.findIndex(column => column.channelId === item.dataValues.channelId)
      const { id, channelId, channelName, category } = item.dataValues
      if (index === -1) {
        const dict = {
          id,
          channelId,
          channelName
        }
        dict.children = [category]
        columnRes.push(dict)
      } else {
        columnRes[index].children.push(category)
      }
    })
    return columnRes
  }
}

module.exports = TreeService
